﻿using BackData;
using Domain.Quality;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.Equipment;

namespace Team.API.Applocation.Hanldler.Equipment
{
    /// <summary>
    /// 设备删除命令处理器
    /// 实现MediatR的IRequestHandler接口，用于处理设备删除逻辑，返回包含删除结果的APIResult
    /// </summary>
    public class DeleteEquipmentHandler : IRequestHandler<DeleteEquipmentCommand, APIResult<int>>
    {
        private readonly IRepository<Equipmentmodel> equiRep;
        /// <summary>
        /// 构造函数，注入设备仓储接口
        /// </summary>
        /// <param name="equiRep">设备领域模型的仓储实例，封装数据访问逻辑</param>
        public DeleteEquipmentHandler(IRepository<Equipmentmodel> equiRep)
        {
            this.equiRep = equiRep;
        }
        /// <summary>
        /// 处理设备删除的核心方法
        /// 异步执行设备查询，执行逻辑删除（标记IsDel为true），并返回删除结果
        /// </summary>
        /// <param name="request">设备删除命令，包含待删除设备的ID</param>
        /// <param name="cancellationToken">用于异步操作取消的令牌</param>
        /// <returns>包含删除结果、状态码和提示信息的APIResult</returns>
        public async Task<APIResult<int>> Handle(DeleteEquipmentCommand request, CancellationToken cancellationToken)
        {
            // 根据命令中的设备ID查询设备
            var equipment = await equiRep.GetByIdAsync(request.Id);

            // 执行删除操作（可根据业务需求选择物理删除或逻辑删除）
            // 逻辑删除示例：设置IsDel为true
            equipment.IsDel = true;
            int r= await equiRep.UpdateAsync(equipment);
            if (r > 0)
            {
                // 返回删除成功的结果
                return new APIResult<int>
                {
                    Code = StateCode.OK,
                    Message = "设备删除成功",
                    Result = r
                };
            }
            else
            {
                // 返回删除失败的结果
                return new APIResult<int>
                {
                    Code = StateCode.Fail,
                    Message = "设备删除失败",
                    Result = r
                };
            }
                
        }
    }
}
